﻿#include "ssStateMachine.h"

namespace StarSeeker
{

ssStateMachine::IState::IState()
{
	m_onwer = 0;
	m_stateID = 0;
	m_machine = 0;
	m_fromState = 0;
}

ssStateMachine::ssStateMachine(void* onwer)
	:m_onwer(onwer), m_currentState(0), m_defaultState(0), m_pause(false)
{
}

ssStateMachine::~ssStateMachine()
{
}

void ssStateMachine::Update(int ms)
{
	IState* state = m_currentState.get();
	if (state && !m_pause)
	{
		state->BeforeUpdate();
		if (state == m_currentState.get())
		{
			state->Update(ms);
		}
	}
}

void ssStateMachine::AddState(const std::shared_ptr<IState>& s, bool isDefault)
{
	s->m_machine = this;
	s->m_onwer = m_onwer;
	std::pair<std::map<int, std::shared_ptr<IState> >::iterator, bool> ret = m_states.insert(std::pair<int, std::shared_ptr<IState> >(s->m_stateID, s));
	if (ret.second)
	{
		ret.first->second->OnAttach();
		if (isDefault)
		{
			m_currentState = ret.first->second;
			m_currentState->OnStateBegin();
			m_defaultState = m_currentState;
		}
	}
	else//替换状态
	{
		SwitchState(m_defaultState->m_stateID, 0);//删除替换的状态，先切到默认状态，不能替换默认状态
		m_states.erase(ret.first);
		m_states.insert(std::pair<int, std::shared_ptr<IState> >(s->m_stateID, s));
	}
}

void ssStateMachine::SwitchState(int stateID, void* param)
{
	std::map<int, std::shared_ptr<IState> >::iterator itr = m_states.find(stateID);
	if (itr != m_states.end() && m_currentState->m_stateID != stateID)
	{
		std::shared_ptr<IState> old(m_currentState);
		old->OnStateEnd();
		m_currentState = itr->second;
		m_currentState->m_fromState = old->m_stateID;
		m_currentState->OnStateBegin(param);
	}

}

int ssStateMachine::CurrentStateID()
{
	return m_currentState->m_stateID;
}

}
